<template>
    <div style="padding: 20px">
        <div>
            <el-input placeholder="关键词搜索" v-model="keyword" style="width: 240px;">
                <el-button slot="append" icon="el-icon-search" @click="searchType"></el-button>
            </el-input>
            <el-button icon="el-icon-refresh" circle @click="refreshType" style="width: 40px; margin-left: 8px"
                type="success"></el-button>
            <el-button type="primary" @click="addDialogVisible = true">新增类型</el-button>
        </div>
        <el-table :data="TypeList" style="width: 100%; border-radius: 10px; margin-top: 8px" stripe v-loading="loading">
            <el-table-column type="index" :index="indexMethod" label="序号" width="75" align="center">
            </el-table-column>
            <el-table-column prop="name" label="类型名称" width="160" show-overflow-tooltip align="center"></el-table-column>
            <el-table-column prop="cover" label="类型封面" width="180" show-overflow-tooltip align="center">
                <template slot-scope="scope">
                    <el-image style="height: 100px" :src="scope.row.cover" :preview-src-list="[scope.row.cover]">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100" sortable prop="status" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? "正常" : "禁用" }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" alerign="center"> </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"
                        style="width: 40px"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle style="width: 40px"
                        @click="deleteType(scope.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="width: 40px; margin-top: 8px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="paramsForm.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="paramsForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :visible.sync="dialogVisible" title="修改类型">
            <el-form :model="updateTypeForm" :rules="rules" ref="updateTypeForm" label-width="80px">
                <el-form-item label="类型名称" prop="name">
                    <el-input v-model="updateTypeForm.name" placeholder="请输入类型名称"></el-input>
                </el-form-item>
                <el-form-item label="类型封面" prop="cover">
                    <el-upload class="image-uploader" action="/api/upload/image" :show-file-list="false"
                        :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
                        <img v-if="updateTypeForm.cover" :src="updateTypeForm.cover" class="image">
                        <i v-else class="el-icon-plus image-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="updateTypeForm.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="dialogVisible = false" style="width: 68px" size="medium">取消</el-button>
                <el-button type="primary" @click="updateOneType('updateTypeForm')" style="width: 68px"
                    size="medium">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="addDialogVisible" title="修改类型">
            <el-form :model="addTypeForm" :rules="rules" ref="addTypeForm" label-width="80px">
                <el-form-item label="类型名称" prop="name">
                    <el-input v-model="addTypeForm.name" placeholder="请输入类型名称"></el-input>
                </el-form-item>
                <el-form-item label="类型封面" prop="cover">
                    <el-upload class="image-uploader" action="/api/upload/image" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addTypeForm.cover" :src="addTypeForm.cover" class="image">
                        <i v-else class="el-icon-plus image-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态" required>
                    <el-radio-group v-model="addTypeForm.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="addDialogVisible = false" style="width: 68px" size="medium">取消</el-button>
                <el-button type="primary" @click="addOneType('addTypeForm')" style="width: 68px"
                    size="medium">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getAllCategory, deleteCategoryById, modifyCategory, createCategory } from '@/api/controller/5.type/index'
export default {
    mounted() {
        this.getType();
    },
    data() {
        let keyword = "";
        let TypeList;
        let total = 0;
        let loading = false;
        let dialogVisible = false;
        let addDialogVisible = false;
        return {
            paramsForm: {
                pageSize: 10,
                pageNum: 1,
            },
            updateTypeForm: {
                id: 0,
                name: "",
                cover: "",
                status: 0
            },
            addTypeForm: {
                name: "",
                status: 1,
                cover: "",
            },
            rules: {
                name: [
                    { required: true, message: '请输入类型名称！', trigger: 'change' }
                ],
                cover: [
                    { required: true, message: '请上传类型封面！', trigger: 'change' }
                ],
            },
            keyword,
            TypeList,
            total,
            loading,
            dialogVisible,
            addDialogVisible
        };
    },
    methods: {
        indexMethod(index) {
            return (
                index + 1 + this.paramsForm.pageSize * (this.paramsForm.pageNum - 1)
            );
        },
        searchType() {
            if (this.keyword === "") {
                this.$message.error("搜索关键词不能为空！");
            } else {
                this.paramsForm.key = this.keyword;
                this.getType();
            }
        },
        refreshType() {
            this.paramsForm.key = "";
            this.getType();
        },
        async getType() {
            this.loading = true;
            getAllCategory(
                this.paramsForm.pageNum, this.paramsForm.pageSize
            )
                .then((response) => {
                    const { data } = response;
                    this.TypeList = data.list;
                    this.total = data.total;
                })
                .catch((error) => {
                    this.$message.error(error.message);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        async deleteType(id) {
            this.$confirm('此操作将永久删除该类型, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteCategoryById(id)
                    .then((response) => {
                        const { message } = response;
                        this.$message.success(message);
                        this.getType();
                    })
                    .catch((error) => {
                        this.$message.error(error.message);
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async updateOneType(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    modifyCategory(this.updateTypeForm)
                        .then((response) => {
                            const { message } = response;
                            this.$message.success(message);
                            this.getType();
                            this.dialogVisible = false;
                        })
                        .catch((error) => {
                            this.$message.error(error.message);
                        });
                } else {
                    return false;
                }
            });
        },
        async addOneType(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    createCategory(this.addTypeForm)
                        .then((response) => {
                            const { message } = response;
                            this.$message.success(message);
                            this.getType();
                            this.addDialogVisible = false;
                        })
                        .catch((error) => {
                            this.$message.error(error.message);
                        });
                } else {
                    return false;
                }
            });
        },
        handleEdit(data) {
            Object.assign(this.updateTypeForm, data);
            this.dialogVisible = true;
        },
        handleSizeChange(val) {
            this.paramsForm.pageSize = val;
            this.getType();
        },
        handleCurrentChange(val) {
            this.paramsForm.pageNum = val;
            this.getType();
        },
        handleAvatarSuccess(res) {
            this.addTypeForm.cover = res.data.imageUrl
        },
        handleAvatarSuccess1(res) {
            this.updateTypeForm.cover = res.data.imageUrl
        },
        beforeAvatarUpload(file) {
            let types = ['image/jpeg', 'image/jpg', 'image/png'];
            const isJPG = types.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG、JPEG、PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 20MB!');
            }
            return isJPG && isLt2M;
        }
    },
};
</script>
<style>
.image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.image-uploader .el-upload:hover {
    border-color: #409EFF;
}

.image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 248px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.image {
    width: 248px;
    height: 178px;
    display: block;
}
</style>